package com.linghang.back.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微信公众平台API工具类
 */
@Slf4j
@Component
public class WechatMpUtil {

    @Value("${wechat.mp.app-id}")
    private String appId;

    @Value("${wechat.mp.app-secret}")
    private String appSecret;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    private final StringRedisTemplate redisTemplate;
    
    // Redis中存储微信访问令牌的key
    private static final String WECHAT_ACCESS_TOKEN_KEY = "wechat:mp:access_token";

    public WechatMpUtil(RestTemplateBuilder restTemplateBuilder, StringRedisTemplate redisTemplate) {
        this.restTemplate = restTemplateBuilder.build();
        this.objectMapper = new ObjectMapper();
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取微信访问令牌
     */
    public String getAccessToken() {
        // 从Redis中获取访问令牌
        String accessToken = redisTemplate.opsForValue().get(WECHAT_ACCESS_TOKEN_KEY);
        
        // 如果Redis中有有效的令牌，直接返回
        if (accessToken != null && !accessToken.isEmpty()) {
            log.info("从Redis缓存获取微信访问令牌");
            return accessToken;
        }

        // Redis中没有令牌或令牌已过期，获取新的访问令牌
        String url = String.format(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                appId, appSecret);

        try {
            JsonNode response = restTemplate.getForObject(url, JsonNode.class);
            
            if (response != null && response.has("access_token")) {
                accessToken = response.get("access_token").asText();
                int expiresIn = response.get("expires_in").asInt();
                // 提前5分钟过期，设置到Redis中
                redisTemplate.opsForValue().set(WECHAT_ACCESS_TOKEN_KEY, accessToken, expiresIn - 300, TimeUnit.SECONDS);
                log.info("获取微信访问令牌成功并缓存到Redis，有效期: {} 秒", expiresIn - 300);
                return accessToken;
            } else {
                log.error("获取微信访问令牌失败: {}", response);
                throw new RuntimeException("获取微信访问令牌失败");
            }
        } catch (Exception e) {
            log.error("获取微信访问令牌异常", e);
            throw new RuntimeException("获取微信访问令牌异常", e);
        }
    }

    /**
     * 获取公众号文章列表
     */
    public JsonNode getBizArticleList(String offset, String count) {
        String url = "https://api.weixin.qq.com/cgi-bin/freepublish/batchget?access_token=" + getAccessToken();
        
        try {
            // 转换为整数
            int offsetInt = Integer.parseInt(offset);
            int countInt = Integer.parseInt(count);
            
            Map<String, Object> params = new HashMap<>();
            params.put("offset", offsetInt);
            params.put("count", countInt);
            //1 表示不返回content字段，0表示正常返回，默认为0
            params.put("no_content", 1);

            String requestBody = objectMapper.writeValueAsString(params);
            log.info("请求URL: {}", url);
            log.info("请求参数: {}", requestBody);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
            
            // 先接收为字符串，然后手动解析JSON
            String responseStr = restTemplate.postForObject(url, entity, String.class);
            log.info("响应结果(原始): {}", responseStr);
            
            // 将字符串解析为JSON
            try {
                JsonNode response = objectMapper.readTree(responseStr);
                log.info("响应结果(JSON): {}", response);
                return response;
            } catch (Exception e) {
                log.error("解析JSON响应失败: {}", e.getMessage());
                throw new RuntimeException("解析微信响应数据失败: " + responseStr, e);
            }
        } catch (Exception e) {
            log.error("获取公众号文章列表异常: {}", e.getMessage(), e);
            throw new RuntimeException("获取公众号文章列表异常", e);
        }
    }

        /**
     * 解析文章数据
     */
    public Map<String, Object> parseArticle(JsonNode article) {
        Map<String, Object> result = new HashMap<>();
        try {
            log.info("解析文章数据: {}", article);
            
            // 提取文章ID (article_id)
            String articleId = article.path("article_id").asText("");
            result.put("wechatArticleId", articleId);
            
            // 处理content.news_item结构 (首篇文章)
            if (article.has("content") && article.path("content").has("news_item") && 
                article.path("content").path("news_item").isArray() && 
                article.path("content").path("news_item").size() > 0) {
                
                JsonNode newsItem = article.path("content").path("news_item").get(0);
                
                // 提取标题
                result.put("title", newsItem.path("title").asText(""));
                
                // 提取作者
                result.put("author", newsItem.path("author").asText(""));
                
                // 提取摘要
                result.put("digest", newsItem.path("digest").asText(""));
                
                // 提取内容
                result.put("content", newsItem.path("content").asText(""));
                
                // 提取封面图
                result.put("coverUrl", newsItem.path("thumb_url").asText(""));
                
                // 提取文章URL
                result.put("wechatUrl", newsItem.path("url").asText(""));
                
                // 其他字段
                result.put("showCoverPic", newsItem.path("show_cover_pic").asInt(0) == 1);
                result.put("needOpenComment", newsItem.path("need_open_comment").asInt(0) == 1);
                result.put("onlyFansCanComment", newsItem.path("only_fans_can_comment").asInt(0) == 1);
                result.put("isDeleted", newsItem.path("is_deleted").asBoolean(false));
                
                // 设置类型
                result.put("type", "微信公众号文章");
                
                // 获取发布时间 (优先使用content节点的时间)
                String createTime = article.path("create_time").asText("");
                String updateTime = article.path("update_time").asText("");
                
                if (!updateTime.isEmpty()) {
                    result.put("publishDate", updateTime);
                } else if (!createTime.isEmpty()) {
                    result.put("publishDate", createTime);
                } else {
                    // 默认使用当前时间戳
                    result.put("publishDate", String.valueOf(System.currentTimeMillis() / 1000));
                }
            } else {
                // 处理其他可能的格式 (兼容旧结构)
                log.warn("未找到content.news_item结构，尝试使用其他方式解析");
                
                // 提取标题和内容
                String title = article.path("title").asText("");
                String content = article.path("content").asText("");
                String coverUrl = "";
                String wechatUrl = "";
                
                result.put("title", title);
                result.put("content", content);
                result.put("type", "微信公众号文章");
                
                // 获取封面URL
                if (article.has("thumb_url")) {
                    coverUrl = article.path("thumb_url").asText("");
                } else if (article.has("image_url")) {
                    coverUrl = article.path("image_url").asText("");
                } else if (article.has("cover")) {
                    coverUrl = article.path("cover").asText("");
                }
                result.put("coverUrl", coverUrl);
                
                // 获取文章URL
                if (article.has("url")) {
                    wechatUrl = article.path("url").asText("");
                }
                result.put("wechatUrl", wechatUrl);
                
                // 获取发布时间
                String updateTime = "";
                if (article.has("update_time")) {
                    updateTime = article.path("update_time").asText("");
                } 
                if (updateTime.isEmpty() && article.has("create_time")) {
                    updateTime = article.path("create_time").asText("");
                }
                if (updateTime.isEmpty() && article.has("publish_time")) {
                    updateTime = article.path("publish_time").asText("");
                }
                if (updateTime.isEmpty()) {
                    // 默认使用当前时间戳
                    updateTime = String.valueOf(System.currentTimeMillis() / 1000);
                }
                result.put("publishDate", updateTime);
            }
            
        } catch (Exception e) {
            log.error("解析文章数据异常: {}", e.getMessage(), e);
        }
        return result;
    }
} 